//
//  BKMyAction.m
//  bestkeep
//
//  Created by 武探 on 2016/11/3.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKMyAction.h"
#import "BKMyViewController.h"
#import "BKUserStatusInfo.h"
#import "MJExtension.h"
#import "BKUserUnitRequestAPI.h"
#import "BKMyCommon.h"
#import "BKUserLoginController.h"
#import "UT_User.h"
#import "BK_my_EditAddressVC.h"
#import "BK_my_ShippingAddress.h"
//#import "BK_my_CouponVC.h"
#import "BK_My_CupVC.h"
#import "SystemMessageVC.h"
#import "BKUserNavigationBarCustomViewController.h"
#import "BKSystemMessageMannager.h"
#import "BKMyUserFavorStoreController.h"
#import "BKUserRealNameAuthReshultController.h"
#import "BKUserRealNameAuthController.h"
#import "AppDelegate.h"
#import "BKUserRequestUrl.h"
#import "UTLogin.h"
#import "Mediator+BKMy.h"
#import "BKUserMyCouponController.h"
#import "BK_StorePay_VC.h"

typedef void(^BKMyUserSecretKey)(id obj);

NSString *const BKMyUserIsLoginKey = @"BKMyUserIsLoginKey";
NSString *const BKMyUserInfoAccountKey = @"BKMyUserInfoAccountKey";
NSString *const BKMyUserGetTGTKey = @"BKMyUserGetTGTKey";
NSString *const BKMyUserGetUTOUUPlatformSTkey = @"BKMyUserGetUTOUUPlatformSTkey";
NSString *const BKMyUserGetBestKeepPlateformSTKey = @"BKMyUserGetBestKeepPlateformSTKey";
NSString *const BKMyUserInfoGetUserIdKey = @"BKMyUserInfoGetUserIdKey";
NSString *const BKMyUserInfoUserVistorIdKey = @"BKMyUserInfoUserVistorIdKey";
NSString *const BKMyUserInfoUserNickNameKey = @"BKMyUserInfoUserNickNameKey";
NSString *const BKMyUserGetUnreadMessageNumber = @"unreadMessageNumber";
//用户的认证状态
NSString * const BKMyUserInfoUserAuthStatusKey = @"BKMyUserInfoUserAuthStatusKey";//已认证 未认证

@interface BKMyAction ()<UIAlertViewDelegate>

@property (nonatomic,strong)BKMyAction  * myAction;
@property (nonatomic,strong)UIAlertView * alertView;

@end


@implementation BKMyAction

+(BKMyAction *)share
{
    static  BKMyAction * myAction;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        myAction = [[BKMyAction alloc]init];
    });
    
    return myAction;
}


-(UIViewController *)myViewController {
    BKMyViewController *controller = [[BKMyViewController alloc] init];
    return controller;
}

//获取用户信息
-(NSDictionary*)myUserInfo {
    
    BKUserStatusInfo * statusInfo = [BKUserStatusInfo currentUser];
    
    NSNumber  * isLogin;
    isLogin = [NSNumber numberWithBool:statusInfo.isLogin];
    NSMutableDictionary * userInfoDict = [[NSMutableDictionary alloc]init];
    [userInfoDict setValue:isLogin forKey:BKMyUserIsLoginKey];
    [userInfoDict setValue:statusInfo.userNum forKey:BKMyUserInfoAccountKey];
    [userInfoDict setValue:statusInfo.TGT forKey:BKMyUserGetTGTKey];
    [userInfoDict setValue:statusInfo.LoginST forKey:BKMyUserGetUTOUUPlatformSTkey];
    [userInfoDict setValue:statusInfo.ServiceST forKey:BKMyUserGetBestKeepPlateformSTKey];
    [userInfoDict setValue:statusInfo.userId forKey:BKMyUserInfoGetUserIdKey];
    [userInfoDict setValue:statusInfo.visitorCode forKey:BKMyUserInfoUserVistorIdKey];
    [userInfoDict setValue:statusInfo.nickName forKey:BKMyUserInfoUserNickNameKey];
    [userInfoDict setValue:statusInfo.realAuthStatus forKey:BKMyUserInfoUserAuthStatusKey];
    return userInfoDict;
}

//获取st方法
/*
 * serverceUrl 请求服务的URL
 */
-(id)getSTWithDataDict:(NSDictionary *)dict
{
    NSString * serverceUrl = dict[@"severceUrl"];
    BkMyCompleteBlock1 finishBlock = dict[@"resultBlock"];
    BKUserStatusInfo * statusInfo = [BKUserStatusInfo currentUser];
    [BKUserUnitRequestAPI getSTWithTGT:statusInfo.TGT service:serverceUrl completeBlock:^(id obj, NSString  *data, NSError *error) {
        
        if (data) {
            
            NSString * st = data;//[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            finishBlock(obj,st,nil);
        } else {
            
            finishBlock(obj,nil,error);
        }
        
    }];
    
    return nil;
}

-(id)setDevelopEnvironmentWithDict:(NSDictionary *)dict
{
    NSString * numStr = dict[@"envirValue"];
    NSInteger num = [numStr integerValue];
    [UT_User setScene:num];
    return nil;
}

//登录
-(id)userGoToLoginWithDict:(NSDictionary *)dict
{
    UIViewController * originalVC = dict[@"controller"];
    BKLoginSuccessBlock finishBlock = dict[@"resultBlock"];
    BKUserLoginController * LoginvVC = [BKUserLoginController userGotoLoginWithBlcok:^() {
        
        NSLog(@"登录成功啦。。。。。。。。。。。。。。。。。。。。。");
        finishBlock();
    }];
    
    BKUserNavigationBarCustomViewController * nav = [[BKUserNavigationBarCustomViewController alloc]initWithRootViewController:LoginvVC];
    
    [originalVC presentViewController:nav animated:YES completion:nil];
    
    return nil;
}
//退出登录
-(id)userLoginOut
{
    BKMyAction * myAction = [BKMyAction share];
    [myAction userLoginOutClassMethed];
    return nil;
}

-(id)userLoginOutClassMethed
{
    [BKUserStatusInfo clearHistoryData];
    
    if (IOS8) {
        
        UIViewController * pushVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的身份令牌已过期, 为了您的账号安全, 请重新登录。" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            BKUserLoginController * LoginvVC = [BKUserLoginController userGotoLoginWithBlcok:^() {
                
                NSLog(@"登录成功啦。。。。。。。。。。。。。。。。。。。。。");
            }];
            
            BKUserNavigationBarCustomViewController * nav = [[BKUserNavigationBarCustomViewController alloc]initWithRootViewController:LoginvVC];
            
            [pushVC presentViewController:nav animated:YES completion:nil];
            
        }];
        
        [alert addAction:action];
        [pushVC presentViewController:alert animated:YES completion:nil];
        
    } else {

        if (!self.alertView) {
        
            UIAlertView * alrtV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的身份令牌已过期, 为了您的账号安全, 请重新登录。" delegate: nil
                                                  cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
            alrtV.delegate = self;
            self.alertView = alrtV;
            [alrtV show];
        }
    }
    
    return nil;
}

//实名认证
-(id)realNameAuthVCWithDict:(NSDictionary *)paraDict
{
    UINavigationController * pushNav = paraDict[@"nav"];
    NSDictionary * dataDict1 = paraDict [@"dataDict"];
            
            NSDictionary * dict = dataDict1;
            NSNumber * isSuccess = dict[@"success"];
            NSInteger  numstr = [isSuccess integerValue];
            if (numstr == 1) {
                
                BKUserRealNameAuthReshultController * resultRealNameVc = [[BKUserRealNameAuthReshultController alloc]init];
                NSDictionary *dataDic = [dict objectForKey:@"data"];
                
                resultRealNameVc.type = [[dict objectForKey:@"data"] objectForKey:@"realAuthStatus"];
                
                if (![resultRealNameVc.type integerValue]) {
                    
                    BKUserRealNameAuthController * realNameVc = [[BKUserRealNameAuthController alloc]init];
                    [pushNav pushViewController:realNameVc animated:YES];
                } else {
                    
                    resultRealNameVc.realName = [dataDic objectForKey:@"realName"];
                    resultRealNameVc.realPersonalId = [dataDic objectForKey:@"certypeNumber"];
                    resultRealNameVc.rejectReason = [dataDic objectForKey:@"reject"];
                    resultRealNameVc.realAuthStatusStr = [dataDic objectForKey:@"realAuthStatusStr"];
                    [pushNav pushViewController:resultRealNameVc animated:YES];
        }
     }
    
    return nil;
}




-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  
    if (buttonIndex == 0) {
        
        BKUserLoginController * LoginvVC = [BKUserLoginController userGotoLoginWithBlcok:^() {
            
            NSLog(@"登录成功啦。。。。。。。。。。。。。。。。。。。。。");
        }];
        
        BKUserNavigationBarCustomViewController * nav = [[BKUserNavigationBarCustomViewController alloc]initWithRootViewController:LoginvVC];
        
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UIViewController * currentVc = [self getCurrentViewControllerWithWindow:delegate.window];
        
        [currentVc presentViewController:nav animated:YES completion:nil];
    }

}

//进入我的VIP界面
-(id)goToVIPWithDataDict:(NSDictionary *)dict
{
    UIViewController * targetVC = dict[@"targetVC"];
    
    NSString *urlStr = [UserPassPortStr stringByAppendingString:AccountLoginUrlStr];
    NSString *tgt = [[Mediator sharedInstance]BKMyUserInfo][BKMyUserGetTGTKey];
    NSString *stUrl = [NSString stringWithFormat:@"%@/%@", urlStr, tgt];
    NSString *value = [UserWebStr stringByAppendingString:@"profile/vip"];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:value,@"service", nil];
    NSDictionary *headDic = [UTLogin getSTHeadDictionary:dic params:dic strurl:stUrl];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    for (NSString *key in [headDic allKeys]) {
        
        NSString *value = [headDic objectForKey:key];
        [manager.requestSerializer setValue:value forHTTPHeaderField:key];
    }
    [BKIndicationView showInView:targetVC.view];
    [manager POST:stUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [BKIndicationView dismiss];
        NSLog(@"%@", responseObject);
        
        NSString *st = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        BKUserMyCouponController *coupon = [[BKUserMyCouponController alloc] init];
        coupon.requestUrl = [NSString stringWithFormat:@"%@%@%@",UserWebStr,@"profile/vip?ticket=",st];
        [targetVC.navigationController pushViewController:coupon animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [BKIndicationView dismiss];
        if (error.code==502) {
            [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
        }else{
            [HUD showErrorMessage:error.localizedDescription];
        }
    }];
    
    return  nil;
}


//获取当前控制器

- (UIViewController *) getCurrentViewControllerWithWindow:(UIWindow *)window
{
    UINavigationController *navigationController;
    
    UITabBarController *tabBarController = (UITabBarController *)window.rootViewController;
    
    if (tabBarController.selectedIndex == 0) {
        
        navigationController = window.rootViewController.childViewControllers.firstObject;
        
    }else if (tabBarController.selectedIndex == 1) {
        
        navigationController = window.rootViewController.childViewControllers[1];
        
    }else if (tabBarController.selectedIndex == 2) {
        
        navigationController = window.rootViewController.childViewControllers[2];
        
    }else if (tabBarController.selectedIndex == 3) {
        
        navigationController = window.rootViewController.childViewControllers[3];
        
    }else {
        
        navigationController = window.rootViewController.childViewControllers.firstObject;
    }
    
    return navigationController.viewControllers.lastObject;
    
}


-(id)userRegisterEMMobWithDict:(NSDictionary *)dict
{
    UIApplication * application = dict[@"application"];
    NSString * EaseMobKey = dict[@"EaseMobKey"];
    NSDictionary * optionDict = dict[@"launchOptions"];

    [[EaseMob sharedInstance]registerSDKWithAppKey:EaseMobKey apnsCertName:nil];
    [[EaseMob sharedInstance]application:application didFinishLaunchingWithOptions:optionDict];
    
    return nil;
}

//获取未读消息数
/*
 * dict = @{@"userId":"mjunuhjhjhu"};
 *
 */
-(id)getUnreadMessageNumber
{
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    if (userInfo.isLogin) {
        
        [BKUserUnitRequestAPI getUnreadMessageNumberWithUserid:nil resultBlock:^(id obj, NSError *error) {
            
            if (obj) {
                
                NSDictionary * dataDict = obj;
                if ([dataDict objectForKey:@"success"]) {
                    
                    NSDictionary * dict = dataDict[@"data"];
                    NSString * uNreadNum = [NSString stringWithFormat:@"%@",dict[@"unreadCount"]];
                    if ([uNreadNum intValue] > 0) {
                        
                    } else {
                        
                        uNreadNum = @"";
                    }
                    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                    [userInfo.realm  beginWriteTransaction];
                    
                    userInfo.unreadMessageNum = uNreadNum;
                    
                    [userInfo.realm commitWriteTransaction];
                }
                
            } else {
                
                NSLog(@"未读消息数网络请求失败");
            }
            
        }];

    }
    
    return nil;
}

//获取未读消息数
-(NSDictionary *)uNreadMessageNumber
{
    NSDictionary * dict = [[NSDictionary alloc]init];
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    [dict setValue:userInfo.unreadMessageNum forKey:BKMyUserGetUnreadMessageNumber];
    return dict;
}

//获取deviceToken
-(id)getDeviceTokenWithDict:(NSDictionary *)dict
{
    NSString * deviceTokenStr = dict[@"deviceToken"];
    BKUserStatusInfo * userInf = [BKUserStatusInfo currentUser];
    [userInf.realm beginWriteTransaction];
    userInf.deveiceToken = deviceTokenStr;
    [userInf.realm commitWriteTransaction];
  
    return nil;
}

//获取我的收藏控制器
-(UIViewController *)getMyFavorController
{
    BKMyUserFavorStoreController * favorVC = [[BKMyUserFavorStoreController alloc]init];
    return favorVC;
}

-(UIViewController *)editShippingAddress:(NSDictionary *)address {
    BK_my_EditAddressVC *shippingAddressVC = [[BK_my_EditAddressVC alloc] init];
    BOOL isAdd = [address[@"iaAdd"] boolValue];
    if (isAdd == 1) {
        shippingAddressVC.isAddShippingAddress = YES;//从新增进地址按钮来
        shippingAddressVC.isShowSwitch = YES;//显示switch
    } else {
        [shippingAddressVC dict:address];
    }
    BOOL isCome_OD = [address[@"isCome_OD"] boolValue];
    if (isCome_OD) {
        shippingAddressVC.isCome_OD = YES;//从订单拿到
    }
    return shippingAddressVC;
}

- (UIViewController *)toBK_CouponVC {
    BK_My_CupVC*couponVC = [[BK_My_CupVC alloc] init];
    return couponVC;
//    BK_my_CouponVC *couponVC = [[BK_my_CouponVC alloc] init];
//    return couponVC;
}

- (UIViewController *)toSystemMessageVC {
    SystemMessageVC *systemMessage = [[SystemMessageVC alloc] init];
    return systemMessage;
}
//支付码VC
- (UIViewController *)toBK_StorePayVC {
    
    BK_StorePay_VC *storePayVC = [[BK_StorePay_VC alloc] init];
    return storePayVC;
}

//获取系统消息
-(id)getMessageStatusWithApplicationFinishLaunchingWithOptionsDataDict:(NSDictionary *)dataDict
{
    UIApplication * application = dataDict[@"Application"];
    NSDictionary * options = dataDict[@"options"];
    BKSystemMessageMannager * mannager = [BKSystemMessageMannager mananger];
    [mannager getMessageStatusWithApplication:application didFinishLaunchingWithOptions:options];
   
    return nil;
}

-(id)getMessgaeWhthApplicationDidBecomeActiveWithDataDict:(NSDictionary *)dataDict
{
    UIApplication * application = dataDict[@"Application"];
    BKSystemMessageMannager * mannager = [BKSystemMessageMannager mananger];
    [mannager getMessgaeWhthApplicationDidBecomeActive:application];
    return nil;
}

-(id)getMessageWhenApplicationWillEnterForegroundWithDataDict:(NSDictionary *)dataDict
{
    UIApplication * application = dataDict[@"Application"];
    BKSystemMessageMannager * mannager = [BKSystemMessageMannager mananger];
    [mannager getMessageWhenApplicationWillEnterForeground:application];
    return nil;
}

-(id)getMessageNumWhenApplicationReceiveRemoteNotificationWithDataDict:(NSDictionary *)dataDict
{
    UIApplication * application = dataDict[@"Application"];
    NSDictionary * options = dataDict[@"options"];
    UIWindow * window = dataDict[@"window"];
    BKSystemMessageMannager * manager = [BKSystemMessageMannager mananger];
    [manager getMessageNumWhenApplication:application didReceiveRemoteNotification:options window:window];
    return nil;
}

// 获取用户支付密钥
-(id)getUserSecretKey:(NSDictionary *)dic {
    
    BKMyUserSecretKey block = dic[@"UserSecretKey"];
    [BKUserLoginController getUserSecretKey:^(id obj) {
        
        block(obj);
    }];
    
    return nil;
}


//将一个字符串写入文件
+ (BOOL)writeUTOUUPayStatus {
    
    NSArray *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[libraryPath objectAtIndex:0] stringByAppendingPathComponent:@"UTOUUPayStatus"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:nil];
    }
    NSData *data = [@"YES" dataUsingEncoding:NSUTF8StringEncoding];
    return  [fileManager createFileAtPath:filePath contents:data attributes:nil];
}

+ (BOOL)writeUTOUUOrderStatus {
    
    NSArray *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[libraryPath objectAtIndex:0] stringByAppendingPathComponent:@"UTOUUOrderStatus"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:nil];
    }
    NSData *data = [@"YES" dataUsingEncoding:NSUTF8StringEncoding];
    return  [fileManager createFileAtPath:filePath contents:data attributes:nil];
}

//从文件中读取字符串
+ (NSString *)readStringWithUTOUUOrderStatus {
    
    NSArray *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[libraryPath objectAtIndex:0] stringByAppendingPathComponent:@"UTOUUOrderStatus"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    } else {
        return nil;
    }
}

+ (NSString *)readStringWithUTOUUPayStatus {
    
    NSArray *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[libraryPath objectAtIndex:0] stringByAppendingPathComponent:@"UTOUUPayStatus"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    } else {
        return nil;
    }
}

@end
